<template>
  <ECharts class="chart" :option="option" />
</template>

<script setup>
import ECharts from 'vue-echarts'
import { ref, computed, onMounted } from 'vue'
import * as echarts from 'echarts';

const props = defineProps({
  tableData: {
    type: Array,
    required: true
  }
})

const formatBarData = () => {
  const regionMap = {}
  props.tableData.forEach(item => {
    const region = item.region
    const data = Number(item.data)
    regionMap[region] = (regionMap[region] || 0) + data
  })
  
  const regions = Object.keys(regionMap)
  const values = Object.values(regionMap)
  const maxValue = Math.max(...values) || 10000
  
  return {
    xData: regions,
    yData: values,
    maxValue
  }
}

const option = computed(() => {
  // 数据为空时返回基础配置避免报错
  if (props.tableData.length === 0) {
    return {
      title: { text: '数据加载中...' },
      xAxis: {},
      yAxis: {}
    }
  }
  
  const barData = formatBarData()
  
  // 安全的渐变颜色配置
  const gradientColors = [
    { offset: 0, color: '#65B581' },
    { offset: 1, color: '#FD665F' }
  ].filter(item => item.color); // 过滤无效颜色
  
  return {
    title: {
      text: '各城市诈骗比例',
      top: 10,
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        return `${params.seriesName}<br/>${params.name}: ${params.value}`
      }
    },
    visualMap: {
      top: 'top',
      right: 10,
      color: ['#ff5428', '#ffd768'],
      calculable: true,
      min: 0,
      max: barData.maxValue
    },
    dataZoom: [
      {
        type: 'slider',
        xAxisIndex: 0,
        start: 0,
        end: 30,
        height: 20,
        bottom: 10
      }
    ],
    grid: {
      top: '15%',
      bottom: '25%',
      left: '5%',
      right: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: barData.xData,
      axisLabel: {
        rotate: 45,
        interval: 0,
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      name: '诈骗数量',
      nameGap: 20
    },
    series: [{
      name: '诈骗数量',
      type: 'bar',
      data: barData.yData,
      itemStyle: {
        // 渐变颜色安全配置
        color: gradientColors.length === 2 
          ? new echarts.graphic.LinearGradient(0, 0, 0, 1, gradientColors)
          : '#65B581',
        borderRadius: 4
      },
      label: {
        show: true,
        position: 'top',
        fontSize: 10
      },
      barWidth: 12
    }]
  }
})
</script>

<style scoped>
.chart {
  width: 100%;
  height: 600px;
}
</style>